package com.gaogzhen.model;

import com.alibaba.fastjson.JSON;
import com.gaogzhen.geetest.GeetestLib;
import com.gaogzhen.geetest.GeetestLibResult;
import com.gaogzhen.utils.IpUtil;
import io.swagger.annotations.ApiModel;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * @author Administrator
 * @version 1.0
 * @description 极验校验信息
 * @date 2022-09-18 10:27
 */
@Data
@ApiModel(value = "极验校验信息")
@Slf4j
public class GeetestForm {
    /**
     * 极验认证相关信息
     */
    private String geetest_validate;
    private String geetest_seccode;
    private String geetest_challenge;
    private String uuid;

    public void authenticate(GeetestLib geetestLib, RedisTemplate<String, Object> redisTemplate) {
        String challenge = this.getGeetest_challenge();
        String seccode = this.getGeetest_seccode();
        String validate = this.getGeetest_validate();

        int status = Integer.parseInt(Objects.requireNonNull(redisTemplate.opsForValue().get(GeetestLib.GEETEST_SERVER_STATUS_SESSION_KEY)).toString());
        String userId = redisTemplate.opsForValue().get(GeetestLib.GEETEST_SERVER_USER_KEY + ":" + this.getUuid()).toString();
        GeetestLibResult result = null;
        if (status == 1) {
            Map<String, String> paramMap = new HashMap<>();
            paramMap.put("user_id", userId);
            paramMap.put("client_type", "web");
            ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            paramMap.put("ip_address", IpUtil.getIpAddr(servletRequestAttributes.getRequest()));
            result = geetestLib.successValidate(challenge, validate, seccode, paramMap);
        } else {
            result = geetestLib.failValidate(challenge, validate, seccode);
        }

        if (result.getStatus() != 1) {
            log.error("验证异常===" + JSON.toJSONString(result));
            throw new RRException("极验验证码异常！");
        }
    }
}
